package util

import (
	"bytes"
	"encoding/binary"
	"math/rand"
	"os"
)

// GetGOENV 获取应用当前的运行模式
func GetGOENV() string {
	return os.Getenv("GO_ENV")
}

/*Krand 生成随机数
* size 随机码的位数
* kind 0    // 纯数字
       1    // 小写字母
       2    // 大写字母
       3    // 数字、大小写字母
*/
func Krand(size int, kind int) string {
	ikind, kinds, result := kind, [][]int{[]int{10, 48}, []int{26, 97}, []int{26, 65}}, make([]byte, size)
	isAll := kind > 2 || kind < 0
	// rand.Seed(time.Now().UnixNano())
	for i := 0; i < size; i++ {
		if isAll { // random ikind
			ikind = rand.Intn(3)
		}
		scope, base := kinds[ikind][0], kinds[ikind][1]
		result[i] = uint8(base + rand.Intn(scope))
	}
	return string(result)
}

// Int64ToBytes 将整形int64转换为 byte[]
func Int64ToBytes(num int64) ([]byte, error) {
	buff := bytes.NewBuffer([]byte{})
	err := binary.Write(buff, binary.BigEndian, num)

	return buff.Bytes(), err
}

// Int32ToBytes 将整形int32转换为 byte[]
func Int32ToBytes(num int32) ([]byte, error) {
	buff := bytes.NewBuffer([]byte{})
	err := binary.Write(buff, binary.BigEndian, num)

	return buff.Bytes(), err
}

// BytesToInt64 将 byte[] 转换为 int64
func BytesToInt64(bs []byte) (int64, error) {
	buff := bytes.NewBuffer(bs)
	var num int64
	err := binary.Read(buff, binary.BigEndian, &num)

	return num, err
}

// BytesToInt32 将 byte[] 转换为 int32
func BytesToInt32(bs []byte) (int32, error) {
	buff := bytes.NewBuffer(bs)
	var num int32
	err := binary.Read(buff, binary.BigEndian, &num)

	return num, err
}
